#include "setdata.h"
#include <QDebug>
#include <QByteArray>


SetData::SetData()
{

}

bool SetData::addNewDevice()
{
    int listsize=devicelist.getdataSize();
    QVariantList Dlist=GetData::getVariant_Device();
    if(Dlist.count()>0)
    {
        for(int i=listsize;i<Dlist.count();i++)
        {
            devicelist.addDevice(Dlist.at(i));
        }
    }

    return (devicelist.getdataSize()==Dlist.size());
}

bool SetData::addNewCode()
{
    int listsize=codelist.getdataSize();
    QVariantList Clist=GetData::getVariant_Code();
    if(Clist.count()>0)
    {
        for(int i=listsize;i<Clist.count();i++)
        {
            QString deviceId=Clist.at(i).value<QVariantMap>()["deviceId"].toString();
            int deviceIndex=devicelist.getIndexByDeviceId(deviceId);
            codelist.addCode(Clist.at(i),deviceIndex);
            Device* device=devicelist.getpdataByIndex(deviceIndex);
            Code* code=codelist.getpdataByIndex(codelist.getdataSize()-1);
            device->deviceCodes.append(code);
        }
    }

    return (codelist.getdataSize()==Clist.size());
}



void SetData::reloadDevice(int id)
{
    QVariantList Dlist=GetData::getVariant_Device(id);
    if(Dlist.count()>0)
    {
       devicelist.updateDevice(Dlist.at(0));
    }
}


bool SetData::Update_ServerSendTaskState(QString serverid,QString sendQN,int state){

    //bool execOk=false;
    QString sql="update hj212data_sendtask set sendNotOk="+QString::number(state)+" where serverId='"+serverid+"' AND sendQN='"+sendQN+"';";

    return sqldate->EXEC(sql);
}

bool SetData::Update_ServerSendTasksendQN(QString serverid,QString sendQN,QString newsendQN){

    //bool execOk=false;
    QString sql="update hj212data_sendtask set sendQN='"+newsendQN+"', sendNotOk=sendNotOk+1 where serverId='"+serverid+"' AND sendQN='"+sendQN+"';";

    return sqldate->EXEC(sql);
}



bool SetData::Update_Device(QString json){

    bool execOk=false;
    QVariantMap dbdata=JsonHelper::getObject(json);

    //qDebug()<<JsonHelper::getJson(dbdata);

    if(dbdata.keys().size()>0)
    {

        if(dbdata["deviceName"].isNull()) return false;
        if(dbdata["devicePort"].isNull()) return false;
        if(dbdata["deviceAddr"].isNull()) return false;
        if(dbdata["protocolIdHex"].isNull()) return false;


        //dbdata["protocolIdHex"]=dbdata["protocolId"].toString();  dbdata.remove("protocolId");

        if(dbdata["id"].isNull())
        {
            dbdata.remove("id");
            execOk=sqldate->INSERT("device",dbdata);
            if(execOk)
            {
                addNewDevice();
            }
        }
        else
        {
            execOk=sqldate->UPDATE("device",dbdata);
            if(execOk)
            {

                reloadDevice(dbdata["id"].toInt());
            }

        }

    }
    return execOk;
}
